﻿using AutoMapper;
using MediatR;
using ProduceBasicData.Api.Application.Command.RBAC.Department;
using ProduceBasicData.Api.DTO.RBACDto;
using ProduceBasicData.Domain.RBAC;
using ProduceBasicData.ErrorCode;
using ProduceBasicData.Infrastructure.Interface;

namespace ProduceBasicData.Api.Application.Handler.RBAC.Department
{
     /// <summary>
    /// 获取所有部门的处理器（不分页）
    /// </summary>
    public class GetAllDepartmentHandler : IRequestHandler<GetAllDepartmentCommand, ApiResult<List<DepartmentsDto>>>
    {
        private readonly IBaseRespository<DepartmentModel> _departmentRepository;
        private readonly IMapper _mapper;

        public GetAllDepartmentHandler(IBaseRespository<DepartmentModel> departmentRepository, IMapper mapper)
        {
            _departmentRepository = departmentRepository;
            _mapper = mapper;
        }

        public async Task<ApiResult<List<DepartmentsDto>>> Handle(GetAllDepartmentCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<List<DepartmentsDto>>();

            try
            {
                // 查询所有「未删除」的部门
                var departments = await _departmentRepository.GetAllAsync();
                var query = departments.Where(x => x.Isdel == false);

                // 映射为 DTO 列表
                var departmentDtos = query.Select(x => new DepartmentsDto
                {
                    Id = x.Id,
                    DepartmentName = x.DepartmentName,
                    ParentId = x.ParentId,
                    SortOrder = x.SortOrder,
                    Leader = x.Leader,
                    Phone = x.Phone,
                    Email = x.Email,
                    State = x.State,
                    CreateName = x.CreateName,
                    CreateTime = x.CreateTime,
                    UpdateName = x.UpdateName,
                    UpdateTime = x.UpdateTime,
                    Isdel = x.Isdel
                }).ToList();

                result.Data = departmentDtos;
                result.Code = ApiEnum.Success;
                result.Msg = "查询所有部门成功";
            }
            catch (Exception ex)
            {
                result.Code = ApiEnum.Failed;
                result.Msg = $"查询异常: {ex.Message}";
                result.Data = new List<DepartmentsDto>();
            }

            return result;
        }
    }
}
